package com.cheer.ba.view.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.cheer.ba.R;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.Constants;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.model.CouponCardModel;
import com.cheer.ba.model.OilSendModel;
import com.cheer.ba.model.PayInfoModel;
import com.cheer.ba.model.QyePayInfoModel;
import com.cheer.ba.pay.PayCommon;
import com.cheer.ba.presenter.impl.CardGroupPresenter;
import com.cheer.ba.presenter.impl.OilMealPresenter;
import com.cheer.ba.utils.Currency;
import com.cheer.ba.utils.LogUtils;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.view.base.BaseCommAty;
import com.cheer.ba.view.base.CommonAdapter;
import com.cheer.ba.view.base.ViewHolder;
import com.cheer.ba.widget.MyListView;
import com.google.gson.Gson;
import com.pingplusplus.android.Pingpp;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 支付界面
 *
 * @author HQ
 *         created at 2017/5/13 0013 11:43
 */
public class PayAty extends BaseCommAty implements AdapterView.OnItemClickListener {

    @BindView(R.id.id_recharge_cardid_rela)
    RelativeLayout mRelaCardNum;
    //卡号
    @BindView(R.id.id_oil_card_num_txt)
    TextView mTxtCardNum;

    //付款金额
    @BindView(R.id.id_pay_money_txt)
    TextView mTxtPayMoney;

    //支付提醒
    @BindView(R.id.id_pay_remind_txt)
    TextView mTxtPayRemind;

    //支付方式
    @BindView(R.id.id_pay_way_listv)
    MyListView mPayWayListV;

    private CommonAdapter<PayInfoModel> mAdapter;

    private List<PayInfoModel> mPayWays = new ArrayList<PayInfoModel>();

    //套餐id
    private String productId;
    //油卡id
    private String oilCardId;
    //支付原价
    private String amount;
    //支付金额
    private String money;
    //手续费
    private String feeAmount;
    //卡号
    private String mCardNum;
    //记录支付方式
    private String channel;

    private PayInfoModel mPayInfoModel;

    @BindView(R.id.id_free_card_txt)
    TextView mTxtCouPon;
    //记录优惠券id
    private String couponId;
    //优惠券
    private CardGroupPresenter mDiscountPresenter;
    //是否可以点击优惠券 true 可以点击
    private boolean isClick;

    //刷新方式
    private boolean isRefresh = false;
    //记录从哪个界面跳转
    private int page_from;

    //记录柴油批发下单界面
    private OilSendModel oilSendModel;

    /**
     * 充值界面跳转
     *
     * @param activity
     * @param productId 套餐id
     * @param oilCardId 油卡id
     * @param amount    支付原价
     * @param feeAmount 手续费
     */
    public static void startPayAty(Activity activity, int page, String productId, String oilCardId, String amount, String mpayMoney, String feeAmount, String mCardNum) {
        Intent intent = new Intent(activity, PayAty.class);
        intent.putExtra(IntentKey.General.KEY_PAGE, page);
        intent.putExtra(IntentKey.Oil.KEY_OIL_PRODUCTID, productId);
        intent.putExtra(IntentKey.Oil.KEY_OIL_CARD_ID, oilCardId);
        intent.putExtra(IntentKey.General.KEY_PAY_AMOUNT, amount);
        intent.putExtra(IntentKey.General.KEY_PAY_MONEY, mpayMoney);
        intent.putExtra(IntentKey.General.KEY_PAY_FEEAMOUNT, feeAmount);
        intent.putExtra(IntentKey.General.KEY_CARD_NUM, mCardNum);
        activity.startActivity(intent);
    }

    /**
     * 去激活
     *
     * @param activity
     * @param page      哪个界面跳转
     * @param oilCardId 油卡id
     * @param amount    支付原价
     * @param feeAmount 手续费
     */
    public static void start2PayAty(Activity activity, int page, String oilCardId, String amount, String mpayMoney, String feeAmount, String mCardNum) {
        Intent intent = new Intent(activity, PayAty.class);
        intent.putExtra(IntentKey.General.KEY_PAGE, page);
        intent.putExtra(IntentKey.Oil.KEY_OIL_CARD_ID, oilCardId);
        intent.putExtra(IntentKey.General.KEY_PAY_AMOUNT, amount);
        intent.putExtra(IntentKey.General.KEY_PAY_MONEY, mpayMoney);
        intent.putExtra(IntentKey.General.KEY_PAY_FEEAMOUNT, feeAmount);
        intent.putExtra(IntentKey.General.KEY_CARD_NUM, mCardNum);
        activity.startActivity(intent);
    }

    /**
     * 柴油批发下单界面
     *
     * @param activity
     * @param page     哪个界面跳转
     */
    public static void start3PayAty(Activity activity, int page, OilSendModel oilSendModel) {
        Intent intent = new Intent(activity, PayAty.class);
        intent.putExtra(IntentKey.General.KEY_PAGE, page);
        intent.putExtra(IntentKey.General.KEY_MODEL, oilSendModel);
        activity.startActivity(intent);
    }

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_pay, null, false));
    }

    @Override
    public boolean hasDataInPage() {
        return isRefresh;
    }

    @Override
    public void initPresenter() {
        presenter = new OilMealPresenter();
        mDiscountPresenter = new CardGroupPresenter();
        mDiscountPresenter.attachView(this);
    }

    @Override
    public void initView() {
        setTitleText("确认订单");
        page_from = getIntent().getIntExtra(IntentKey.General.KEY_PAGE, Constants.DEFAULTVALUE);
        if (page_from == IntentCode.General.JUMP_RECHARGE) {
            //柴油充值
            productId = getIntent().getStringExtra(IntentKey.Oil.KEY_OIL_PRODUCTID);
            oilCardId = getIntent().getStringExtra(IntentKey.Oil.KEY_OIL_CARD_ID);
            amount = getIntent().getStringExtra(IntentKey.General.KEY_PAY_AMOUNT);
            money = getIntent().getStringExtra(IntentKey.General.KEY_PAY_MONEY);
            feeAmount = getIntent().getStringExtra(IntentKey.General.KEY_PAY_FEEAMOUNT);
            mCardNum = getIntent().getStringExtra(IntentKey.General.KEY_CARD_NUM);
            mRelaCardNum.setVisibility(View.VISIBLE);
            mTxtCardNum.setText(StringUtils.replaceBankString(mCardNum, 0));
        } else if (page_from == IntentCode.General.JUMP_CARD_DETAIL) {
            //油卡激活
            oilCardId = getIntent().getStringExtra(IntentKey.Oil.KEY_OIL_CARD_ID);
            amount = getIntent().getStringExtra(IntentKey.General.KEY_PAY_AMOUNT);
            money = getIntent().getStringExtra(IntentKey.General.KEY_PAY_MONEY);
            feeAmount = getIntent().getStringExtra(IntentKey.General.KEY_PAY_FEEAMOUNT);
            mCardNum = getIntent().getStringExtra(IntentKey.General.KEY_CARD_NUM);
            mRelaCardNum.setVisibility(View.VISIBLE);
            mTxtCardNum.setText(StringUtils.replaceBankString(mCardNum, 0));
        } else if (page_from == IntentCode.General.JUMP_CARD_ORDER) {
            //柴油批发界面
            oilSendModel = (OilSendModel) getIntent().getSerializableExtra(IntentKey.General.KEY_MODEL);
            money = oilSendModel.mMayPay;
        }
        mTxtPayMoney.setText(money + "元");

        //获得优惠券
        mDiscountPresenter.getMyDiscountList(false, (int) (Double.parseDouble(money) * 100) + "");

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            mTxtPayRemind.setVisibility(View.VISIBLE);
        }
        EventBus.getDefault().register(this);
    }

    @Override
    public void initData() {
        mPayWays.clear();
        List<PayInfoModel> pays = (List<PayInfoModel>) ((OilMealPresenter) presenter).getData(3, page_from != IntentCode.General.JUMP_CARD_ORDER);
        mPayWays.addAll(pays);
        mAdapter = new CommonAdapter<PayInfoModel>(aty, mPayWays, R.layout.adp_pay_way) {
            @Override
            public void convert(ViewHolder helper, PayInfoModel item) {
                helper.setImageResource(R.id.id_logo_img, item.getPayLogo());
                helper.setText(R.id.id_pay_title_txt, item.getPayTitle());
                helper.setText(R.id.id_pay_desc_txt, item.getPayDesc());
                if (checkMap.get(helper.getPosition(), false)) {
                    helper.getViewById(R.id.id_choose_pay_way_img).setVisibility(View.VISIBLE);
                } else {
                    helper.getViewById(R.id.id_choose_pay_way_img).setVisibility(View.GONE);
                }
            }
        };
        mPayWayListV.setAdapter(mAdapter);
        mPayWayListV.setOnItemClickListener(this);
        mAdapter.setCheckAtPosFalse(0, true);
        mAdapter.notifyDataSetChanged();
        channel = mPayWays.get(0).getPayWay();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventUpdate(BaseEvent event) {
        if (TextUtils.equals(IntentKey.Coupon.COUPON_MONEY, event.type)) {
            couponId = event.id;
            String m = event.money;
            int type = event.couponType;
            String mPay = "";
            if (type == 1) {
                //折扣券
                showText(StringUtils.removePoint(Currency.return2Point(m)) + "折");
                mPay = Currency.returnDollarPoint(money, m);
            } else if (type == 2) {
                //代金券
                showText("-" + Currency.returnDollar(m));
                LogUtils.LogD("haha===", Double.parseDouble(money) + "---");
                LogUtils.LogD("haha---", (Double.parseDouble(m) / 100) + "---");
                mPay = (Double.parseDouble(money) - (Double.parseDouble(m) / 100)) + "";
            } else {
                mPay = money + "";
            }
            double d = Double.parseDouble(mPay);
            if (d <= 0) {
                mTxtPayMoney.setText("0元");
            } else {
                String s = StringUtils.retain2Point(d);
                LogUtils.LogD("payaty", s + "-=-=-=-=-=");
                mTxtPayMoney.setText(s + "元");
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        mAdapter.setCheckAtPosFalse(position, true);
        channel = ((PayInfoModel) mAdapter.getItem(position)).getPayWay();
    }

    @OnClick({R.id.id_sure_pay_btn, R.id.id_choose_free_card_view})
    public void onClick(View mView) {
        switch (mView.getId()) {
            //支付
            case R.id.id_sure_pay_btn:
                isRefresh = true;
                if (StringUtils.isEmpty(channel)) {
                    SVProgressHUD.showInfoWithStatus(aty, "请选择支付方式");
                } else if (StringUtils.isEmpty(money)) {
                    SVProgressHUD.showInfoWithStatus(aty, "支付金额有问题,请重新提交");
                } else {
                    if (TextUtils.equals(channel, PayCommon.QIYE_PAY)) {
                        //弹出登录弹出框
                        ((OilMealPresenter) presenter).showPayDialog();
                    } else {
                        if (page_from == IntentCode.General.JUMP_CARD_ORDER) {
                            //柴油批发
                            ((OilMealPresenter) presenter).oilSend(channel, couponId, oilSendModel);
                        } else {
                            ((OilMealPresenter) presenter).rechargeCard(StringUtils.isEmpty(productId) ? "0" : productId, amount, feeAmount, channel, couponId);
                        }
                    }
                }
                break;
            //优惠券
            case R.id.id_choose_free_card_view:
                if (isClick) {
                    Intent intent = new Intent(aty, DiscountCouponAty.class);
                    intent.putExtra(IntentKey.General.KEY_PAY_MONEY, money);
                    showActivity(aty, intent);
                }
                break;
        }
    }

    @Override
    public <T> void updateViewWithLoadMore(T t, boolean loadMore, String tag) {
        if (null != t) {
            if (TextUtils.equals(ConstantTag.MY_CARD_GROUP, tag)) {
                List<CouponCardModel> cards = (List<CouponCardModel>) t;
                if (null != cards) {
                    if (cards.isEmpty()) {
                        isClick = false;
                        showText("无可用优惠券");
                    } else {
                        isClick = true;
                        showText(cards.size() + "张可用优惠券");
                    }
                } else {
                    isClick = false;
                    showText("无可用优惠券");
                }
            }
        }
    }

    public void showText(String desc) {
        mTxtCouPon.setText(desc);
        if (isClick) {
            mTxtCouPon.setTextColor(getResources().getColor(R.color.red));
        } else {
            mTxtCouPon.setTextColor(getResources().getColor(R.color.color_999999));
        }
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        if (null != t) {
            if (TextUtils.equals(ConstantTag.RECHARGE_SUCCESS, tag)) {
                //获取订单成功
                mPayInfoModel = (PayInfoModel) t;

                String charge = new Gson().toJson(mPayInfoModel);
                Pingpp.createPayment(aty, charge);
            } else if (TextUtils.equals(ConstantTag.QYE_PAY_SUCCESS, tag)) {
                //企业支付成功
                QyePayInfoModel mQyePayInfoModel = (QyePayInfoModel) t;

                ((OilMealPresenter) presenter).qyePayCallBack(productId, oilCardId, mQyePayInfoModel.orderId, couponId);
            } else if (TextUtils.equals(ConstantTag.DATA_SUCCESS_FULL, tag)) {
                //充值成功
                if (page_from == IntentCode.General.JUMP_CARD_DETAIL) {
                    SVProgressHUD.showSuccessWithStatus(aty, "激活成功");
                } else {
                    SVProgressHUD.showSuccessWithStatus(aty, "充值成功");
                }
                BaseEvent event = new BaseEvent();
                event.type = IntentKey.Oil.OIL_ACTIVITY_SUCCESS;
                event.id = oilCardId;
                event.money = amount;
                EventBus.getDefault().post(event);

                BaseEvent event1 = new BaseEvent();
                event1.type = IntentKey.Login.KEY_NOTICE_PAY;
                EventBus.getDefault().post(event1);

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showActivity(aty, PaySuccessAty.class);
                        finish();
                    }
                }, 2000);
            } else if (TextUtils.equals(ConstantTag.CHECK_PW_SUCCESS, tag)) {
                //校验密码成功
                if (page_from == IntentCode.General.JUMP_CARD_DETAIL) {
                    //激活
                    ((OilMealPresenter) presenter).activityOilCard(amount, feeAmount, couponId);
                } else if (page_from == IntentCode.General.JUMP_RECHARGE) {
                    //柴油充值--企业划扣
//                    ((OilMealPresenter) presenter).qyePay(couponId, productId, amount, feeAmount);
                    ((OilMealPresenter) presenter).qyePullMoney(oilCardId, amount);

                }
            } else if (TextUtils.equals(ConstantTag.QYE_PULL_SUCCESS, tag)) {
                //企业划扣成功
                SVProgressHUD.showSuccessWithStatus(aty, "充值成功,一个工作日内到账");
                BaseEvent event = new BaseEvent();
                event.type = IntentKey.Oil.OIL_ACTIVITY_SUCCESS;
                event.id = oilCardId;
                EventBus.getDefault().post(event);

                BaseEvent event1 = new BaseEvent();
                event1.type = IntentKey.Login.KEY_NOTICE_PAY;
                EventBus.getDefault().post(event1);

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 2000);
            } else if (TextUtils.equals(ConstantTag.ACTIVITY_CARD_SUCCESS, tag)) {
                //激活获取订单成功
                mPayInfoModel = (PayInfoModel) t;
                if (TextUtils.equals(channel, PayCommon.QIYE_PAY)) {
                    //企业支付回调
                    ((OilMealPresenter) presenter).qyePayCallBack(StringUtils.isEmpty(productId) ? "0" : productId, oilCardId, mPayInfoModel.orderId, couponId);
                } else {
                    //ping++支付回调
                    String charge = new Gson().toJson(mPayInfoModel);
                    Pingpp.createPayment(aty, charge);
                }
            } else if (TextUtils.equals(ConstantTag.OIL_SEND_SUCCESS, tag)) {
                //柴油批发订单获取成功
                mPayInfoModel = (PayInfoModel) t;
                //ping++支付回调
                String charge = new Gson().toJson(mPayInfoModel);
                Pingpp.createPayment(aty, charge);
            } else if (TextUtils.equals(ConstantTag.OIL_SEND_CALLBACK_SUCCESS, tag)) {
                //柴油批发回调成功
                SVProgressHUD.showSuccessWithStatus(aty, "支付成功");

                BaseEvent event = new BaseEvent();
                event.type = ConstantTag.OIL_SEND_CALLBACK_SUCCESS;
                EventBus.getDefault().post(event);

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showActivity(aty, PaySuccessAty.class);
                        finish();
                    }
                }, 2000);
            }
        }
    }

    /**
     * onActivityResult 获得支付结果，如果支付成功，服务器会收到ping++ 服务器发送的异步通知。
     * 最终支付成功根据异步通知为准
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //支付页面返回处理
        if (requestCode == Pingpp.REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                String result = data.getExtras().getString("pay_result");
                if (TextUtils.equals("success", result)) {
                    //支付成功
                    LogUtils.LogD("支付成功回掉", productId + "--" + oilCardId + "--" + mPayInfoModel.getOrderNo());
                    if (page_from == IntentCode.General.JUMP_CARD_ORDER) {
                        //柴油批发回调
                        ((OilMealPresenter) presenter).oilSendCallBack(mPayInfoModel.getOrderNo());
                    } else {
                        ((OilMealPresenter) presenter).buyOilCard(StringUtils.isEmpty(productId) ? "0" : productId, oilCardId, mPayInfoModel.getOrderNo(), couponId);
                    }
                } else if (TextUtils.equals("cancel", result)) {
                    //支付取消
                    SVProgressHUD.showInfoWithStatus(aty, "支付取消");
                } else if (TextUtils.equals("fail", result)) {
                    //支付失敗
                    SVProgressHUD.showInfoWithStatus(aty, "支付失败");
                } else if (TextUtils.equals("invalid", result)) {
                    //支付控件没有安装
                    SVProgressHUD.showInfoWithStatus(aty, "支付控件没有安装");
                }
                /* 处理返回值
                 * "success" - payment succeed
                 * "fail"    - payment failed
                 * "cancel"  - user canceld
                 * "invalid" - payment plugin not installed
                 */
                String errorMsg = data.getExtras().getString("error_msg"); // 错误信息
                String extraMsg = data.getExtras().getString("extra_msg"); // 错误信息
                LogUtils.LogD("支付信息", result + "---" + errorMsg + "---" + extraMsg);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
